package cn.zzuli.anew;

import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class MusicActivity2 extends AppCompatActivity {
    private MediaPlayer mp;
    private List<Music> musicList;
    private ListView listView;
    private int cur_pos;
    private ImageView iv_play_pause;
  private  TextView name;
  private  TextView singer;
  private  ImageView imageView;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music2);
         name=findViewById(R.id.name);
         singer=findViewById(R.id.singer);
         imageView=findViewById(R.id.imageView5);

        iv_play_pause = findViewById(R.id.imageView3);
        mp = new MediaPlayer();

        //音乐播放完时，播放下一首
        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                next();
            }
        });
        musicList = getMusic();

        listView = findViewById(R.id.lv);
        listView.setAdapter(new BaseAdapter() {
            @Override
            public int getCount() {
                return musicList.size();
            }

            @Override
            public Object getItem(int position) {
                return musicList.get(position);
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                convertView = LayoutInflater.from(MusicActivity2.this)
                        .inflate(R.layout.music_item, parent, false);
                TextView title = convertView.findViewById(R.id.textView);
                TextView artist = convertView.findViewById(R.id.textView2);
                TextView duration = convertView.findViewById(R.id.textView3);
                ImageView iv_music = convertView.findViewById(R.id.imageView);

                Music music = musicList.get(position);
                title.setText(music.getTitle());
                artist.setText(music.getArtist());
                duration.setText(formatTime(music.getDuration()));
                Bitmap bitmap = getImage(music.getAlbum_id());
                if (bitmap != null) {
                    iv_music.setImageBitmap(bitmap);
                    imageView.setImageBitmap(bitmap);
                }

                name.setText(music.getTitle());
                singer.setText(music.getArtist());

                return convertView;
            }

        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                play(position);
            }
        });


    }
    //获取音乐列表

    private List<Music> getMusic() {
        List<Music> musics = new ArrayList<>();
        String[] projection = {
               MediaStore.Audio.Media._ID,//歌曲的id
                MediaStore.Audio.Media.TITLE,//歌曲的名称
                MediaStore.Audio.Media.ARTIST,//歌手名
                MediaStore.Audio.Media.DURATION,//歌曲的播放时长
                MediaStore.Audio.Media.DATA,//歌曲文件的路径
                MediaStore.Audio.Media.ALBUM_ID,//专辑名
               MediaStore.Audio.Media.SIZE//歌曲文件的大小
        };
        Cursor cursor = getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                projection, null, null, null);
        while (cursor.moveToNext()) {
            int _id=cursor.getInt(Integer.parseInt("0"));
            String title = cursor.getString(1);
            String artist = cursor.getString(2);
            long duration = cursor.getLong(3);
            String data = cursor.getString(4);
            int album_id = cursor.getInt(Integer.parseInt("5"));
            int size = cursor.getInt(Integer.parseInt("6"));
            System.out.println(_id + ","+title + "," + artist + "," + duration + "," + data + "," + album_id+"," + size);
            musics.add(new Music(_id,title, artist, duration,data,album_id,size));
        }
        cursor.close();
        return musics;
    }

    private Bitmap getImage(int id) {
        int album_id = id;
        String albumArt = getAlbumArt(album_id);
        Bitmap bm = null;
        if (albumArt != null) {
            bm = BitmapFactory.decodeFile(albumArt);
            return bm;
        }
        return null;
    }

    private String getAlbumArt(int album_id) {
        String mUriAlbums = "content://media/external/audio/albums";
        String[] projection = new String[]{"album_art"};
        Cursor cur = this.getContentResolver().query(Uri.parse(mUriAlbums + "/" +
                album_id), projection, null, null, null);
        String album_art = null;
        if (cur.getCount() > 0 && cur.getColumnCount() > 0) {
            cur.moveToNext();
            album_art = cur.getString(0);
        }
        cur.close();
        cur = null;
        return album_art;
    }

    private void play(int position) {
        try {
            mp.reset();
            mp.setDataSource(musicList.get(position).getData());
            mp.prepare();
            mp.start();
            cur_pos = position;
            iv_play_pause.setSelected(mp.isPlaying());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void play_pause(View v) {
        if (mp.isPlaying())
            mp.pause();
        else
            mp.start();

        iv_play_pause.setSelected(mp.isPlaying());
    }

    public void toPrevious(View v) {
        previous();
    }

    public void toNext(View v) {
        next();
    }

    private void next() {
        ++cur_pos;
        if (cur_pos == musicList.size())
            cur_pos = 0;
        play(cur_pos);
    }

    private void previous() {
        --cur_pos;
        if (cur_pos == -1)
            cur_pos = musicList.size() - 1;
        play(cur_pos);

    }

    //将毫秒转换成分秒表示
    private String formatTime(long ms) {
        SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
        return sdf.format(ms);
    }


}